/*
 * © 2024 huayunliufeng保留所有权利, 依据MIT许可证发布。
 * 请勿更改或删除版权声明或此文件头。
 * 此代码是免费软件, 您可以重新分发和/或修改它。
 * 开源是希望它有用, 但不对代码做任何保证。
 * 如有疑问请联系: huayunliufeng@163.com
 */

package io.github.huayunliufeng.common.bean;

import java.util.Objects;

/**
 * 数组索引, 最多支持三维数组，确保数组索引不会小于0。
 *
 * @author huayu 2024/5/10 15:37
 * @version 0.0.4
 * @since 0.0.4
 */
public class ArrayIndex {
    private int i;
    private int j = -1;
    private int k = -1;

    public ArrayIndex(int i) {
        checkIndex(i);
        this.i = i;
    }

    public ArrayIndex(int i, int j) {
        checkIndex(i, j);
        this.i = i;
        this.j = j;
    }

    public ArrayIndex(int i, int j, int k) {
        checkIndex(i, j, k);
        this.i = i;
        this.j = j;
        this.k = k;
    }

    private void checkIndex(int... indexs) {
        for (int index : indexs) {
            if (index < 0) {
                throw new ArrayIndexOutOfBoundsException("数组索引不能小于0。" + index);
            }
        }
    }

    public int i() {
        return i;
    }

    public ArrayIndex i(int i) {
        checkIndex(i);
        this.i = i;
        return this;
    }

    public int j() {
        return j;
    }

    public ArrayIndex j(int j) {
        checkIndex(j);
        this.j = j;
        return this;
    }

    public int k() {
        return k;
    }

    public ArrayIndex k(int k) {
        checkIndex(k);
        this.k = k;
        return this;
    }

    @Override
    public boolean equals(Object obj) {
        if (obj instanceof ArrayIndex) {
            ArrayIndex other = (ArrayIndex) obj;
            return i == other.i && j == other.j && k == other.k;
        }
        return false;
    }

    public boolean equals(int i) {
        return i() == i;
    }

    public boolean equals(int i, int j) {
        return i() == i && j() == j;
    }

    public boolean equals(int i, int j, int k) {
        return i() == i && j() == j && k() == k;
    }

    public static ArrayIndex of(int i) {
        return new ArrayIndex(i);
    }

    public static ArrayIndex of(int i, int j) {
        return new ArrayIndex(i, j);
    }

    public static ArrayIndex of(int i, int j, int k) {
        return new ArrayIndex(i, j, k);
    }

    @Override
    public int hashCode() {
        return Objects.hash(i, j, k);
    }

    @Override
    public String toString() {
        StringBuilder sb = new StringBuilder("ArrayIndex(i=" + i());
        if (j != -1) {
            sb.append(", j=").append(j());
        }
        if (k != -1) {
            sb.append(", k=").append(k());
        }
        return sb.append(")").toString();
    }
}
